﻿using CoreCms.Net.Swagger;
using CoreCms.Net.Swagger.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.OpenApi.Models;
using Silky.Core;
using Swashbuckle.AspNetCore.Filters;
using System;
using System.IO;
using System.Linq;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SwaggerServiceCollectionExtensions
    {
        public static void AddSwaggerService(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddOptions<SwaggerOptions>().Bind(EngineContext.Current.Configuration.GetSection(SwaggerOptions.SwaggerSettings));

            var op = EngineContext.Current.Configuration.
                                                    GetSection(SwaggerOptions.SwaggerSettings)
                                                    .Get<SwaggerOptions>() ?? new SwaggerOptions();

            services.AddSwaggerGen((s) =>
            {
                //遍历出全部的版本，做文档信息展示
                typeof(CustomApiVersion.ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    s.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{op.Name} 接口文档",
                        Description = $"{op.Name} HTTP API " + version,
                        // Contact = new OpenApiContact { Name = apiName, Email = "", Url = new Uri("") },
                    });
                    s.OrderActionsBy(o => o.RelativePath);
                });

                //生成API XML文档
                var basePath = AppContext.BaseDirectory;
                var xmlPath = Path.Combine(basePath, op.FileName);
                s.IncludeXmlComments(xmlPath);

                // 开启加权小锁
                s.OperationFilter<AddResponseHeadersFilter>();
                s.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token，传递到后台
                s.OperationFilter<SecurityRequirementsOperationFilter>();

                // 必须是 oauth2
                s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });
            });
        }
    }
}